package com.scut.fy.common.web.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;

/**
 * 使用雪花算法产生分布式id
 *
 * @author JY
 * @version 1.0
 * @date 2021/10/14
 */
public class SnowflakeIdGenerator {
    private static final Logger log = LoggerFactory.getLogger(SnowflakeIdGenerator.class);
    private long workerId = 0L;
    private long datacenterId = 0L;
    private Snowflake snowflake = IdUtil.getSnowflake();

    @PostConstruct
    public void init() {
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器id: {}", workerId);
        } catch (Exception e) {
            log.error("找不到当前的ip地址");
        }
    }

    public synchronized long getId() {
        return snowflake.nextId();
    }

    public synchronized long getId(long workerId) {
        Snowflake snowflake = IdUtil.getSnowflake(workerId);
        return snowflake.nextId();
    }

    public synchronized long getId(long workerId, long datacenterId) {
        Snowflake snowflake = IdUtil.getSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }

//    public static void main(String[] args) {
//        System.out.println(new SnowflakeIdGenerator().snowflakeId());
//    }
}
